package com.example.pan.ui.file

import android.annotation.SuppressLint
import android.content.Context
import android.content.pm.ActivityInfo
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.util.Log
import android.view.SurfaceHolder
import android.view.View
import android.view.WindowInsetsController
import android.view.WindowManager
import android.widget.RelativeLayout
import android.widget.SeekBar
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.isVisible
import com.example.pan.R
import com.example.pan.databinding.ActivityMediaPlayerBinding
import com.example.pan.ext.fullScreen
import com.hi.dhl.binding.viewbind
import dagger.hilt.android.AndroidEntryPoint
import tv.danmaku.ijk.media.player.IMediaPlayer
import tv.danmaku.ijk.media.player.IjkMediaPlayer
import tv.danmaku.ijk.media.player.IjkTimedText


@AndroidEntryPoint
class MediaPlayerActivity : AppCompatActivity(),
    IMediaPlayer.OnPreparedListener,
    IMediaPlayer.OnCompletionListener,
    IMediaPlayer.OnErrorListener,
    IMediaPlayer.OnVideoSizeChangedListener,
    IMediaPlayer.OnTimedTextListener,
    View.OnClickListener {

    private val binding by viewbind<ActivityMediaPlayerBinding>()
    private val mPath: String? by lazy { intent.getStringExtra("url") }
    private val mPlayer: IjkMediaPlayer by lazy {
        IjkMediaPlayer().also {
            it.setOnPreparedListener(this)
            it.setOnCompletionListener(this)
            it.setOnErrorListener(this)
            it.setOnVideoSizeChangedListener(this)
            it.setOnTimedTextListener(this)
        }
    }
    private lateinit var handler: Handler

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        IjkMediaPlayer.loadLibrariesOnce(null)
        IjkMediaPlayer.native_profileBegin("libijkplayer.so")


        fullScreen()


        binding.opraa.setOnClickListener {
            requestedOrientation =
                if (requestedOrientation == ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE) {
                    ActivityInfo.SCREEN_ORIENTATION_PORTRAIT
                } else {
                    ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE
                }
        }

        initPlayer()
    }

    private fun initPlayer() {
        binding.surfaceView.holder.addCallback(object : SurfaceHolder.Callback {
            override fun surfaceCreated(holder: SurfaceHolder) {
                mPlayer.setDisplay(binding.surfaceView.holder)


                this@MediaPlayerActivity.mPath?.let {
                    mPlayer.setDataSource(it, mapOf(Pair("User-Agent", "pan.baidu.com")))
                    mPlayer.prepareAsync()
                    binding.loadingDialog.isVisible = true
                }

            }

            override fun surfaceChanged(
                holder: SurfaceHolder,
                format: Int,
                width: Int,
                height: Int
            ) {


            }

            override fun surfaceDestroyed(holder: SurfaceHolder) {

            }

        })


        binding.seekbar.setOnSeekBarChangeListener(object : SeekBar.OnSeekBarChangeListener {
            override fun onProgressChanged(seekBar: SeekBar?, progress: Int, fromUser: Boolean) {
            }

            override fun onStartTrackingTouch(seekBar: SeekBar?) {
            }

            override fun onStopTrackingTouch(seekBar: SeekBar?) {
                mPlayer.seekTo(mPlayer.duration * seekBar?.progress!! / 100)
            }

        })

        handler = Handler(Looper.getMainLooper()) {
            if (mPlayer.isPlaying && it.what == 0) {
                refresh()
                handler.sendEmptyMessageDelayed(0, 1000)
            }
            true
        }

        binding.speed.setOnClickListener(this)
        binding.backBtn.setOnClickListener(this)
        binding.play.setOnClickListener(this)

    }

    private fun initSurfaceView() {
        val wm = this.getSystemService(Context.WINDOW_SERVICE) as WindowManager
        val width = wm.defaultDisplay!!.width
        val height = wm.defaultDisplay!!.height

        val layoutParams = (binding.surfaceView.layoutParams) as RelativeLayout.LayoutParams
        layoutParams.width = width
        layoutParams.height = width * width / height
        binding.surfaceView.layoutParams = layoutParams
    }

    @SuppressLint("SetTextI18n")
    private fun refresh() {
        val cur = mPlayer.currentPosition / 1000
        val duration = mPlayer.duration / 1000
        val curSecond = cur % 60
        val curMinute = cur / 60
        val totalSecond = duration % 60
        val totalMinute = duration / 60
        binding.timeText.text = "$curMinute:$curSecond/$totalMinute:$totalSecond"
        binding.seekbar.progress = (cur * 100 / duration).toInt()
    }

    override fun onDestroy() {
        super.onDestroy()
        mPlayer.stop()
        mPlayer.release()
    }

    override fun onPrepared(p0: IMediaPlayer?) {
        binding.loadingDialog.isVisible = false

        p0?.start()
        binding.play.setImageResource(R.drawable.ic_pause_black_24dp)
        handler.sendEmptyMessageDelayed(0, 0)

    }

    override fun onCompletion(p0: IMediaPlayer?) {

    }

    override fun onError(p0: IMediaPlayer?, p1: Int, p2: Int): Boolean {
        binding.loadingDialog.isVisible = false
        finish()
        Toast.makeText(applicationContext, "加载失败", Toast.LENGTH_SHORT).show()
        return false
    }

    override fun onVideoSizeChanged(p0: IMediaPlayer?, p1: Int, p2: Int, p3: Int, p4: Int) {
        initSurfaceView()

    }

    override fun onTimedText(p0: IMediaPlayer?, p1: IjkTimedText?) {
        Log.e("IMediaPlayer", "${p1?.text}")
    }

    override fun onClick(v: View?) {
        when (v?.id) {
            R.id.back_btn -> finish()
            R.id.speed -> mPlayer.setSpeed(2.0f)
            R.id.play -> {
                if (mPlayer.isPlaying) {
                    mPlayer.pause()
                    binding.play.setImageResource(R.drawable.ic_play_arrow_black_24dp)
                } else {
                    mPlayer.start()
                    binding.play.setImageResource(R.drawable.ic_pause_black_24dp)
                    handler.sendEmptyMessageDelayed(0, 0)
                }
            }
        }
    }

}